import { apiInterceptors, createUser, deleteUser, getRoleList, getUserList, updateUser } from '@/client/api';
import { Button, Form, Input, Modal, Select, Space, Table, Tag, message } from 'antd';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { PaginationResult, RoleInfo, UserInfo, UserRequest } from '@/client/api/auth';

const UserManagement = () => {
  const { t } = useTranslation();
  const [users, setUsers] = useState<PaginationResult<UserInfo>>({
    items: [],
    total_count: 0,
    total_pages: 0,
    page: 1,
    page_size: 20,
  });
  const [roles, setRoles] = useState<RoleInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<UserInfo | null>(null);
  const [form] = Form.useForm();

  // 加载用户列表
  const loadUsers = async (page = 1, pageSize = 20) => {
    setLoading(true);
    try {
      const [, data] = await apiInterceptors(getUserList({ page, page_size: pageSize }));
      if (data) {
        setUsers(data);
      }
    } catch (error) {
      message.error(t('load_failed') || '加载失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载角色列表
  const loadRoles = async () => {
    try {
      const [, data] = await apiInterceptors(getRoleList({ page: 1, page_size: 100 }));
      if (data) {
        setRoles(data.items);
      }
    } catch (error) {
      console.error('Load roles failed:', error);
    }
  };

  useEffect(() => {
    loadUsers();
    loadRoles();
  }, []);

  // 打开新增/编辑弹窗
  const handleAdd = () => {
    setEditingUser(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: UserInfo) => {
    setEditingUser(record);
    form.setFieldsValue({
      username: record.username,
      nick_name: record.nick_name,
      email: record.email,
      phone: record.phone,
      status: record.status,
      remark: record.remark,
      role_ids: record.roles?.map(r => r.id) || [],
    });
    setModalVisible(true);
  };

  // 删除用户
  const handleDelete = (record: UserInfo) => {
    Modal.confirm({
      title: t('confirm_delete') || '确认删除',
      content: `${t('confirm_delete_user') || '确定要删除用户'} "${record.username}" ${t('question_mark') || '吗？'}`,
      okText: t('confirm') || '确定',
      cancelText: t('cancel') || '取消',
      onOk: async () => {
        try {
          const [error] = await apiInterceptors(deleteUser(record.id));
          if (!error) {
            message.success(t('delete_success') || '删除成功');
            loadUsers(users.page, users.page_size);
          }
        } catch (error) {
          message.error(t('delete_failed') || '删除失败');
        }
      },
    });
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const userData: UserRequest = {
        ...values,
        id: editingUser?.id,
      };
      
      console.log('User form values:', values);
      console.log('User data to submit:', userData);

      if (editingUser) {
        // 更新用户
        const [error] = await apiInterceptors(updateUser(editingUser.id, userData));
        if (!error) {
          message.success('更新成功');
          setModalVisible(false);
          loadUsers(users.page, users.page_size);
        } else {
          console.error('Update user error:', error);
        }
      } else {
        // 新增用户
        const [error] = await apiInterceptors(createUser(userData));
        if (!error) {
          message.success('创建成功');
          setModalVisible(false);
          loadUsers(users.page, users.page_size);
        } else {
          console.error('Create user error:', error);
        }
      }
    } catch (error) {
      console.error('Form validation failed:', error);
    }
  };

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '昵称',
      dataIndex: 'nick_name',
      key: 'nick_name',
      width: 120,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
    },
    {
      title: '角色',
      dataIndex: 'roles',
      key: 'roles',
      width: 150,
      render: (roles: RoleInfo[]) => (
        <>
          {roles?.map(role => (
            <Tag key={role.id} color="blue">
              {role.role_name}
            </Tag>
          ))}
        </>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>{status === 1 ? '启用' : '禁用'}</Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'gmt_created',
      key: 'gmt_created',
      width: 160,
      render: (time: string) => (time ? new Date(time).toLocaleString() : '-'),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right' as const,
      render: (_: any, record: UserInfo) => (
        <Space>
          <Button type="link" size="small" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" size="small" danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" onClick={handleAdd}>
          {t('add_user') || '新增用户'}
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={users.items}
        rowKey="id"
        loading={loading}
        scroll={{ x: 1200 }}
        pagination={{
          current: users.page,
          pageSize: users.page_size,
          total: users.total_count,
          onChange: (page, pageSize) => loadUsers(page, pageSize),
          showSizeChanger: true,
          showTotal: total => `共 ${total} 条`,
          position: ['bottomLeft'],
        }}
      />

      <Modal
        title={editingUser ? t('edit_user') || '编辑用户' : t('add_user') || '新增用户'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={600}
        okText={t('confirm') || '确定'}
        cancelText={t('cancel') || '取消'}
      >
        <Form form={form} layout="vertical" style={{ marginTop: 20 }}>
          <Form.Item
            label={t('username') || '用户名'}
            name="username"
            rules={[
              { required: true, message: t('please_input_username') || '请输入用户名' },
              { min: 3, max: 50, message: t('username_length_error') || '用户名长度3-50个字符' },
            ]}
          >
            <Input placeholder={t('please_input_username') || '请输入用户名'} disabled={!!editingUser} />
          </Form.Item>

          {!editingUser && (
            <Form.Item
              label={t('password') || '密码'}
              name="password"
              rules={[
                { required: true, message: t('please_input_password') || '请输入密码' },
                { min: 6, message: t('password_length_error') || '密码长度至少6个字符' },
              ]}
            >
              <Input.Password placeholder={t('please_input_password') || '请输入密码'} />
            </Form.Item>
          )}

          <Form.Item label={t('nickname') || '昵称'} name="nick_name">
            <Input placeholder={t('please_input_nickname') || '请输入昵称'} />
          </Form.Item>

          <Form.Item
            label="邮箱"
            name="email"
            rules={[{ type: 'email', message: t('email_format_error') || '邮箱格式不正确' }]}
          >
            <Input placeholder={t('please_input_email') || '请输入邮箱'} />
          </Form.Item>

          <Form.Item label="手机号" name="phone">
            <Input placeholder={t('please_input_phone') || '请输入手机号'} />
          </Form.Item>

          <Form.Item label={t('roles') || '角色'} name="role_ids">
            <Select
              mode="multiple"
              placeholder={t('please_select_roles') || '请选择角色'}
              options={roles.map(role => ({
                label: role.role_name,
                value: role.id,
              }))}
            />
          </Form.Item>

          <Form.Item label="状态" name="status" initialValue={1}>
            <Select>
              <Select.Option value={1}>{t('active') || '启用'}</Select.Option>
              <Select.Option value={0}>{t('disabled') || '禁用'}</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item label="备注" name="remark">
            <Input.TextArea rows={3} placeholder={t('please_input_remark') || '请输入备注'} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;
